import util from '../../libs/util.js'
import {Message} from 'view-design'
const user = {
    namespaced: true,
    state: {
        UserInfo: {},
    },
    mutations: {
        // 设置用户账号信息
        setUserInfo(state, UserInfo) {

            console.log('setUserInfo', UserInfo)

            state.UserInfo = JSON.parse(JSON.stringify(UserInfo))
            if(UserInfo.userId) {
                localStorage.setItem('iotUserInfo', JSON.stringify(state.UserInfo))
            } else {
                localStorage.removeItem('iotUserInfo')
            }


        },
    },
    actions: {
        // 获取当前账号信息
        getUserInfo({state, commit, dispatch}) {
            return new Promise(resolve => {
                let UserInfoStr = localStorage.getItem('iotUserInfo');
                console.log('UserInfoStr', UserInfoStr)
                console.log('UserInfoStr', UserInfoStr ? '有': '没有', UserInfoStr && UserInfoStr != 'null')
                // UserInfoStr = '';
                if(UserInfoStr && UserInfoStr != 'null' && UserInfoStr != null) {
                    //有用户信息
                    let UserInfo = JSON.parse(UserInfoStr);
                    console.log('有用户信息', UserInfo)
                    commit('setUserInfo', UserInfo);

                    util.get('/shCloud/profile_get').then(res => {
                        console.log('用户信息', res);
                        if(res.status == 200) {
                            state.UserInfo = {
                                ...UserInfo,
                                ...res.data,
                            };
                        } else {
                            if(res.msg === 'token不能为空！') {
                                localStorage.clear();
                                state.UserInfo = null;
                            }


                            console.log('res.msg', res.msg)
                            Message.warning(res.msg || '获取用户信息失败')
                        }

                        resolve(state.UserInfo);
                    }).catch(err => {
                        Message.warning(err || '获取用户信息失败')
                        commit('setUserInfo', null);
                        resolve(null);
                    })

                } else {
                    //没有用户信息
                    commit('setUserInfo', {});
                    resolve({});
                }
            });
        },
    }
}
export default user
